<?php
namespace App\Services;

use App\Logic\LogLogic;
use Illuminate\Http\Client\RequestException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redis;
class TuoYuanService {

    /**
     * @notes 获取请求token
     * @return mixed
     * @throws RequestException
     * @author Evil丿
     * @date 2024/10/28 09:40
     */
    private static function getRequestToken()
    {
        $token = Redis::get('ty:request_token');

        if($token) return $token;

        $path = '/openapi/v1/sign-in';

        $params = [
            'username' => config('services.ty.username'),
            'password' => config('services.ty.password')
        ];

        $url = config('services.ty.host') . $path;

        $response = Http::retry(3, 1000)
            -> timeout(3)
            -> post($url, $params)
            -> throw()
            -> json();

        if(!$response) {
            throw new AccessDeniedHttpException('TY服务请求失败');
        }

        if(!isset($response['code']) || $response['code'] != 0) {
            throw new AccessDeniedHttpException($response['msg']);
        }

        $token = $response['data']['token'];

        $exp = $response['data']['exp'] - time();

        Redis::setex('ty:request_token', $exp, $token);

        return $token;
    }

    /**
     * @notes 发起公共请求
     * @param $path
     * @param $data
     * @param $header
     * @return array|mixed
     * @throws RequestException
     * @author Evil丿
     * @date 2024/10/28 09:40
     */
    private static function commonRequest($path, $data, $method = 'POST')
    {
        $url = config('services.ty.host') . $path;

        $token =  "Bearer " . self::getRequestToken();

        $header = [
            "Authorization" => $token
        ];

        if($method == 'POST') {
            $response = Http::retry(3, 1000)
                -> timeout(3)
                -> withHeaders($header)
                -> post($url, $data)
                -> throw()
                -> json();
        } else {
            $response = Http::retry(3, 1000)
                -> timeout(3)
                -> withHeaders($header)
                -> get($url, $data)
                -> throw()
                -> json();
        }


        if(!$response) {
            throw new AccessDeniedHttpException('TY服务请求失败');
        }

        if($response['code'] != 0) {
            throw new AccessDeniedHttpException($response['msg'] ?? '');
        }

        LogLogic::setTyLogs(time(), $path, $data);

        return $response;
    }

    public static function applyGoods(String $skuName, Array $imgUrls, String $skuSpec = "", String $skuCode = "", String $isStandard = "")
    {
        $data = [
            "skuName"     => $skuName,
            "skuSpec"     => $skuSpec,
            "skuCode"     => $skuCode,
            "isStandard"  => $isStandard ? true : false,
            "imgUrls"     => $imgUrls,
            "callbackUrl" => config('app.url') . '/api/swt/notify/ty/applyGoods',
        ];

        $path = "/openapi/v1/skus/apply";

        $res = self::commonRequest($path, $data);

        return $res['data']['acceptanceId'];
    }

    public static function getApplyGoodsStatus(String $acceptance_id)
    {
        $data = [
            "acceptanceId"     => $acceptance_id,
        ];

        $path = "/openapi/v1/skus/apply";

        $res = self::commonRequest($path, $data, 'GET');

        return $res['data'];
    }

    public static function getGoodsBySku(Array $skuCode)
    {
        $code = trim(implode(',', $skuCode), ',');

        $data = [
            'code' => $code
        ];

        $path = "/openapi/v1/skus";

        $res = self::commonRequest($path, $data,'GET');

        return $res['data'];
    }

    public static function setDeviceInfo(Array $params)
    {
        $data = [
            "cpuId"         => "SWT".$params['imei'],
            "deviceNumber"  => "SWT".$params['machine_code'],
            "deviceId"      => "SWT".$params['device_code'],
            "deviceName"    => $params['machine_name'],
            "message"       => $params['address'],
            "callbackUrl"   => config('app.url')."/api/swt/notify/ty/machine"
        ];

        $path = "/openapi/v1/device";

        $res = self::commonRequest($path, $data);

        return $res;
    }

    public static function getDeviceInfo(Array $params)
    {
        $data = [
            "cpuId" => "SWT".$params['imei']
        ];

        $path = "/openapi/v1/device?";

        $res = self::commonRequest($path, $data,'GET');

        return $res;
    }

    public static function setVideoInfo($order_id, $videos, $skus, $cupId)
    {
        $data = [
            "recogId"     => "SWT" . $order_id,
            "videos"      => $videos,
            "skuScope"    => $skus,
            "deviceCPUId" => "SWT" . $cupId,
            "callbackUrl" => config('app.url')."/api/swt/notify/ty/videos",
            "doorNo"      => "D"
        ];
        $path = "/openapi/v1/recognition";

        $res = self::commonRequest($path, $data);

        return $res;
    }

    public static function getVideoInfo($order_id)
    {
        $data = [
            "recogId"     => "SWT" . $order_id
        ];

        $path = "/openapi/v1/result/".$data['recogId'];

        $res = self::commonRequest($path, $data, "GET");

        return $res;
    }
}
